<template>
    <div class="video-detail-layout">
        <div class="_breadcrumb">
            <Breadcrumb :items="breadcrumbItems" />
        </div>

        <main class="content">
            <header class="article-header">
                <h1>{{ articleContet.title || '' }}</h1>
                <div class="label">
                    <span v-for="item in articleContet.tags" :key="item">{{ item.name }}</span>
                </div>
                <div class="meta">
                    <div class="left">
                        <div class="comment"><img src="/icon/video-detail/time.png" /><span>{{
                            formatDate(articleContet.publishDate) }}</span>
                        </div>
                        <div class="comment"><img src="/icon/video-detail/movie.png" /><span>共 {{ totalLessons }}
                                课时</span></div>
                        <div class="comment"><img src="/icon/detail/eye.png" /><span>浏览量 {{ articleContet.views }}
                                次</span></div>
                        <div class="comment"><img src="/icon/video-detail/download.png" /><span>已下载 {{
                            articleContet.downloads
                                }} 次</span></div>
                    </div>
                    <div class="right">
                        <div class="download comment" @click="downloadFile"
                            v-if="article.channel?.articleModel.code === 'kpzykj'">
                            <img src="/icon/science/download.png" /><span>下载</span>
                        </div>
                        <div class="comment collect" @click="collectHandle(article.collect, article.id)">
                            <img v-if="!article.collect" src="/icon/detail/star.png" />
                            <img v-else src="/icon/detail/star-active.png" />
                            <span>收藏</span>
                        </div>
                        <!-- <div class="comment share"><img src="/icon/detail/wechat.png" /><span>分享</span></div> -->
                    </div>
                </div>
            </header>

            <div class="video-container">
                <div class="video-player">
                    <div class="video-wrapper" v-if="currentVideo.video">
                        <video ref="videoPlayer" class="video-element" :poster="currentVideo.poster" controls>
                            <source :src="currentVideo.video" type="video/mp4">
                        </video>
                    </div>
                    <div class="text" v-if="currentVideo.text">
                        <div v-html="currentVideo.text"></div>
                    </div>
                    <div class="imageList" v-if="currentVideo.imageList">
                        <div v-for="item in currentVideo.imageList" :key="item">
                            <img :src="item.url" alt="">
                        </div>
                    </div>
                    <div class="fileList" v-if="currentVideo.fileList.length > 0">
                        附件列表:
                        <span v-for="item in currentVideo.fileList">
                            <a :href="item.url" target="_blank">{{ item.name }}</a>
                        </span>
                    </div>
                </div>

                <!-- 右侧视频列表 -->
                <div class="video-list">
                    <h3 class="list-title">课程目录</h3>
                    <div class="chapter-group">
                        <div v-for="(chapter, chapterIndex) in videoItems" :key="chapterIndex">
                            <template v-if="chapter.children">
                                <span class="chapter-title">
                                    {{ chapter.name }}
                                </span>
                                <div v-for="(video, videoIndex) in chapter.children" :key="videoIndex"
                                    class="video-item" :class="{
                                        active: selectedChapterIndex === chapterIndex &&
                                            selectedVideoIndex === videoIndex
                                    }" @click="changeVideo(chapterIndex, videoIndex)">
                                    <div class="item-content">
                                        <span class="item-index">{{ videoIndex + 1 }}.</span>
                                        <span class="item-title">{{ video.name }}</span>
                                        <span class="item-duration">{{ video.videoDuration }}</span>
                                    </div>
                                </div>
                            </template>
                            <template v-else>
                                <div class="video-item" :class="{
                                    active: selectedChapterIndex === chapterIndex
                                }" @click="changeVideo(chapterIndex)">
                                    <div class="item-content">
                                        <span class="item-index">{{ chapterIndex + 1 }}.</span>
                                        <span class="item-title">{{ chapter.name }}</span>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</template>
<script setup>
import { formatDate } from '@/utils/date'
const { $fetchAuth } = useNuxtApp()
const props = defineProps({
    article: {
        type: Object,
        default: ''
    },
    breadcrumbItems: {
        type: Array,
        default: () => []
    },
    neighbors: {
        type: Object,
        default: () => ({})
    },
    currentRoute: {
        type: String,
        default: ''
    }
})
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 路径本地化方法
const localePath = useLocalePath()
//获取下载参数
// const { data: downloadParams } = await useAsyncData(
//     'download-params',
//     () => $fetchAuth(`app/api/article/download-params/${props.article.id}`, {
//         method: 'GET'
//     })
// )

// const downloadParamsObj = computed(() => {
//     if (downloadParams.value) {
//         const params = new URLSearchParams(downloadParams.value.data);
//         return Object.fromEntries(params);
//     }
//     return {};
// });

const collectHandle = async (iscollect, id) => {
    try {
        if (!userStore.user) {
            router.push(localePath('/Login'));
            return;
        }

        if (iscollect) {
            const { data: cancleCollect } = await $fetchAuth(`/app/api/core/user-collects/${id}`, {
                method: 'DELETE'
            });
            if (cancleCollect.status === 0) {
                props.article.collect = !iscollect;
            }
            return;
        } else {
            const { data: collect } = await $fetchAuth(`/app/api/core/user-collects`, {
                method: 'POST',
                body: { articleId: id }
            });
            if (collect.status === 0) {
                props.article.collect = !iscollect;
            }
            return;
        }
    } catch (error) {
        console.error('操作失败:', error);
    }
}

const articleContet = computed(() => {
    return props.article
})

// 默认选中第一个视频
const selectedChapterIndex = ref(0)
const selectedVideoIndex = ref(0)
const videoPlayer = ref(null)


const videoItems = computed(() => {

    return props.article.chapterList
})

// 当前视频数据
const currentVideo = computed(() => {
    const chapter = videoItems.value[selectedChapterIndex.value]
    return chapter?.children?.[selectedVideoIndex.value] || chapter
})

//下载文件
const downloadFile = async () => {
    if (!userStore.user) {
        ElMessageBox.confirm('您需要登录才能下载该文件，是否去登录？', '提示', {
            confirmButtonText: '去登录',
            cancelButtonText: '取消',
            closeOnClickModal: false,
            type: 'warning'
        }).then(() => {
            router.push(localePath('/Login') + `?redirect=${encodeURIComponent(route.fullPath)}`);
        }).catch(() => {
            // 用户取消操作
        });
    } else {
        //先获取下载参数
        const downloadParams = ref(null);
        if (!props.article?.id) {
            showError({ statusCode: 404 })
        } else {
            downloadParams.value = await $fetchAuth(`/app/api/article/download-params/${props.article.id}`, {
                method: 'GET',
            })
        }

        const downloadParamsObj = computed(() => {
            if (downloadParams.value) {
                const params = new URLSearchParams(downloadParams.value.data);
                return Object.fromEntries(params);
            }
            return {};
        });

        const { data } = await $fetchAuth(`/app/api/article/download-file/${props.article.id}`, {
            method: 'GET',
            params: {
                downloadType: 'chapter',
                chapterId: currentVideo.value?.id,
                ...downloadParamsObj.value
            }
        })
        const link = document.createElement('a');
        link.href = data.fileUrl;
        link.download = data.fileName
        link.click();
        window.URL.revokeObjectURL(link.href)
        // document.removeChild(link)        
        // window.URL.revokeObjectURL(link);
        // const blob = new Blob([data], { type: 'application/octet-stream' });
        // const url = window.URL.createObjectURL(blob);
        // const link = document.createElement('a');
        // link.href = url;
        // // 获取文件name + 时间戳
        // link.download = `${currentVideo.value?.name + new Date().getTime()}.mp4`;
        // link.click();
        // window.URL.revokeObjectURL(url);
    }
}

watch(() => props.article.chapterList, (newVal) => {
    if (newVal?.length) {
        selectedChapterIndex.value = 0
        selectedVideoIndex.value = 0
    }
}, { immediate: true })

// 切换视频
const changeVideo = (chapterIndex, videoIndex) => {
    selectedChapterIndex.value = chapterIndex
    selectedVideoIndex.value = videoIndex

    // 加载并播放新视频
    nextTick(() => {
        if (videoPlayer.value) {
            videoPlayer.value.load()
            videoPlayer.value.play().catch(error => {
                console.log('视频自动播放被阻止:', error)
            })
        }
    })
}

// 添加课时统计计算属性
const totalLessons = computed(() => {
    return props.article.chapterList?.reduce((total, chapter) => {
        return total + (chapter.children?.length || 0)
    }, 0) || 0
})

</script>
<style scoped lang="scss">
@use '@/assets/scss/main' as *;

.video-detail-layout {
    max-width: 1200px;
    margin: 0rem auto;
    padding-bottom: 2rem;

    .content {
        background: white;
        padding: 1.5rem;
        border-radius: 0.5rem;
        box-shadow: 0 0.125rem 0.75rem rgba(0, 0, 0, 0.1);

        .article-header {
            padding-bottom: 1rem;
            margin-bottom: 1rem;

            h1 {
                color: $mytext-color;
                font-size: 1.2rem;
                text-align: left;
                margin-bottom: 0.5rem
            }

            .label {
                margin: .5rem 0;

                span {
                    display: inline-block;
                    border: 1px solid #044180;
                    padding: .2rem .5rem;
                    border-radius: .2rem;
                    font-size: .8rem;
                    color: #044180;
                    margin-right: .5rem;
                }
            }

            .meta {
                display: flex;
                justify-content: space-between;
                align-items: center;

                .left {
                    display: flex;
                    align-items: center;
                    gap: 1rem;

                    .comment {
                        display: flex;
                        align-items: center;
                        gap: .2rem;
                        font-size: 1rem;
                        color: #666;

                        img {
                            width: 1.3rem;
                            margin-bottom: 1px;
                            height: 1.25rem;
                        }
                    }
                }

                .right {
                    display: flex;
                    align-items: center;
                    gap: 1rem;

                    img {
                        width: 1.3rem;
                        height: 1.3rem;
                    }

                    .comment {
                        display: flex;
                        align-items: center;
                        font-size: 1rem;
                        color: #666666;
                        gap: .2rem;
                        cursor: pointer;

                        &.collect {
                            img {
                                margin-top: -1px;
                            }
                        }
                    }
                }
            }

            @media screen and (max-width: 768px) {
                margin-bottom: 0;
            }
        }

        .video-container {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 30px;
            min-height: 460px;

            .video-player {
                max-width: 60vw;

                .video-wrapper {
                    position: relative;
                    padding-bottom: 56.25%; // 16:9
                    background: #000;
                    border-radius: 8px;
                    overflow: hidden;

                    .video-element {
                        position: absolute;
                        width: 100%;
                        height: 100%;
                    }
                }

                .text {
                    margin-top: 1.5rem;
                }

                .fileList {
                    margin-top: 1.5rem;

                    span {
                        display: inline-block;
                        margin-right: 1rem;
                    }
                }

                .video-title {
                    font-size: 20px;
                    color: #333;
                    margin: 16px 0 8px;
                }

                .video-subtitle {
                    color: #666;
                    font-size: 14px;
                }

                @media screen and (max-width: 768px) {
                    width: 100%;
                    max-width: 100%;
                }
            }

            // .other {
            //     //这里要给一个最大宽度
            //     max-width: 2fr;
            //     .text {
            //         font-size: 1rem;
            //         line-height: 1.8;
            //         color: #333;
            //         margin-bottom: 1rem;
            //     }
            //     .imageList {
            //         img {
            //             width: 100%;
            //             height: auto;
            //             margin-bottom: 1rem;
            //         }
            //     }
            // }
            @media (max-width: 768px) {
                grid-template-columns: 1fr;
            }
        }

        // .video-player {
        //     .video-wrapper {
        //         position: relative;
        //         padding-bottom: 56.25%; // 16:9
        //         background: #000;
        //         border-radius: 8px;
        //         overflow: hidden;

        //         .video-element {
        //             position: absolute;
        //             width: 100%;
        //             height: 100%;
        //             object-fit: cover;
        //         }
        //     }

        //     .video-title {
        //         font-size: 20px;
        //         color: #333;
        //         margin: 16px 0 8px;
        //     }

        //     .video-subtitle {
        //         color: #666;
        //         font-size: 14px;
        //     }
        // }

        .video-list {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 16px;

            .list-title {
                font-size: 18px;
                color: #333;
                margin-bottom: 16px;
            }
        }

        .chapter-group {
            height: auto;
            max-height: 24rem;
            overflow-y: scroll;

            .chapter-title {
                display: inline-block;
                font-weight: 500;
                margin-bottom: 10px;
                color: inherit;
            }

            .video-item {
                padding: 12px;
                margin-bottom: 8px;
                border-radius: 6px;
                cursor: pointer;
                transition: all 0.2s;

                &:hover {
                    background: #e9ecef;
                }

                &.active {
                    background: #1867CA;
                    color: white;

                    .item-duration {
                        color: rgba(255, 255, 255, 0.8);
                    }

                    .item-index {
                        color: white;
                    }
                }

                .item-content {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                }

                .item-index {
                    color: #666;
                    min-width: 20px;
                }

                .item-title {
                    flex: 1;
                    font-size: 14px;
                    line-height: 1.4;
                }

                .item-duration {
                    font-size: 12px;
                    color: #999;
                }
            }
        }
    }
}

@media (max-width: 768px) {
    .video-detail-layout {
        ._breadcrumb {
            padding: 0 .8rem;
        }

        .content {
            padding: .8rem;
            width: 94%;
            margin: 0 auto;

            .article-header {
                h1 {
                    font-size: 1rem;
                }

                .meta {
                    flex-direction: column;
                    align-items: flex-start;
                    gap: 1rem;

                    .left {
                        display: flex;
                        gap: 0.5rem;

                        img {
                            display: none;
                        }
                    }

                    .right {
                        display: flex;
                        gap: 0.5rem;
                    }
                }
            }
        }

        footer {
            flex-direction: column;
            align-items: flex-start;
            gap: 1rem;
        }
    }
}
</style>